package com.zyfdroid.bigdialerkit.utils;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class PermissionUtils {
    private static final String TAG = "PermissionCheck";

    // 需要检查的权限数组
    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.CALL_PHONE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG
    };


    // 检查所有必需权限是否都已授予
    public static boolean hasRequiredPermissions(Context context) {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "缺少权限: " + permission);
                    return false;
                }
            }
        }
        return true;
    }

    // 显示权限请求对话框
    public static void showPermissionDialog(Context ctx) {
        new AlertDialog.Builder(ctx)
                .setTitle("需要权限")
                .setMessage("应用需要以下权限才能正常运行:\n\n" +
                        "- 通话记录权限\n" +
                        "- 电话权限\n" +
                        "- 联系人权限\n\n" +
                        "请前往设置页面授予这些权限")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openAppSettings(ctx);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(ctx, "未授权，部分功能可能会闪退", Toast.LENGTH_SHORT).show();
                    }
                })
                .setCancelable(false) // 禁止点击外部关闭
                .show();
    }

    // 打开应用详情设置页面
    private static void openAppSettings(Context ctx) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", ctx.getPackageName(), null);
        intent.setData(uri);
        try {
            ctx.startActivity(intent);
        } catch (Exception e) {
            // 备用方案：打开通用应用列表
            intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
            ctx.startActivity(intent);
            Log.e(TAG, "无法打开应用详情: " + e.getMessage());
        }
    }

}
